package com.lxc.service.Impl;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/ws/notify/{userId}")
public class NotificationWebSocketEndpoint {

    // 存储用户ID和对应的Session
    private static final ConcurrentHashMap<Integer, Session> sessions = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") Integer userId) {
        sessions.put(userId, session);
        System.out.println("用户 " + userId + " 已连接到 WebSocket");
    }

    @OnClose
    public void onClose(Session session, @PathParam("userId") Integer userId) {
        sessions.remove(userId);
        System.out.println("用户 " + userId + " 已断开 WebSocket 连接");
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        // 可选：处理客户端发来的消息
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        try {
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("发生异常：" + throwable.getMessage());
    }

    // 发送给指定用户的方法
    public static void sendNotificationToUser(Integer userId, String message) {
        Session session = sessions.get(userId);
        if (session != null && session.isOpen()) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
